<template>
    <div class="fillcontain">
        <Header/>

        <div class="form-container" style="padding-top: 20px;">
            <el-form ref="courseForm" status-icon :model="course" label-width="80px" :rules="rules" style="width: 80%;">
                <el-form-item label="年级" required>
                    <el-select v-model="course.gradeId" placeholder="请选择" >
                        <el-option v-for="item in grades" :key="item.id"
                                   :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户名" prop="name" required>
                    <el-input v-model="course.name"></el-input>
                </el-form-item>

                <el-form-item label="简介">
                    <el-input type="textarea" v-model="course.desc" :rows="7"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="createCourse('courseForm')">立即创建</el-button>
                    <el-button>取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>

</template>

<script>
    import {createCourse, getGrades, isExistsCourseName, isExistsLoginName} from "../api/getData";
    import Header from "../components/Header";

    export default {
        name: "CourseList",
        components: {Header},
        data(){
            var validateCourseName = async (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('课程不能为空'));
                }
                // 校验该用户名是否存在
                const isExists = await isExistsCourseName({name:value});
                if(isExists.data.data == true){
                    return callback(new Error('用户名已存在'));
                }
            };
            return{
                grades:[],
                course:{},
                rules:{name:{ validator: validateCourseName, trigger: 'blur' }}
            }
        },
        created(){
            this.init()
        },
        methods:{
            async init(){
                const grade = await getGrades();
                this.grades = grade.data.data;
            },
            async createCourse(form){
                this.$refs[form].validate(async (valid) => {
                    if (valid) {
                        if(!this.course.gradeId){
                            this.$message.warning('请选择年级')
                            return;
                        }
                        console.log(this.course)
                        const res = await createCourse(this.course);
                        if(res.data.code == 0){
                            this.$message('添加课程成功');
                            this.$router.push('/courseList')
                        }
                    }
                });

            }
        }
    }
</script>

<style scoped>

</style>
